﻿using DevExpress.Utils.Mdi;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
namespace B.MESUI.Login.WareHouseManage.IOWareHouse
{
    public partial class CreateIOWareHouseForm : DevExpress.XtraEditors.XtraForm
    {
        private Dictionary<string, int> _barcodeCountDict = new Dictionary<string, int>();

        // 手动声明控件字段
        private TextBox txtBarcodeInput;
        private ListBox listBoxBarcodes;
        private TextBox txtQuantity;
        private Button btnSave;
        private Button btnClose;
        private readonly HttpClient _httpClient = new HttpClient();
        private System.Windows.Forms.ComboBox comboBoxType;
        public delegate void SaveCompletedEventHandler();
        public event SaveCompletedEventHandler SaveCompleted;

        public CreateIOWareHouseForm()
        {
            InitializeComponent();

            // 初始化控件和事件绑定
            InitializeCustomControls(); // 如果你之前已经初始化了控件
        }
        private const int ControlStartX = 350; // 控件起始 X 坐标
        private const int LabelOffsetX = -120; // Label 相对控件的偏移量
        private const int VerticalSpacing = 30; // 控件之间的垂直间距
        private void InitializeCustomControls()
        {
            int startY = 50;

            // 创建条码输入框
            txtBarcodeInput = new TextBox();
            txtBarcodeInput.Location = new Point(ControlStartX, startY);
            txtBarcodeInput.Width = 200;
            this.Controls.Add(txtBarcodeInput);

            // 创建“请扫描条码”标签
            var labelBarcode = new Label();
            labelBarcode.Text = "请扫描条码：";
            labelBarcode.AutoSize = true;
            labelBarcode.Location = new Point(ControlStartX + LabelOffsetX, startY + 5);
            this.Controls.Add(labelBarcode);



            // 创建条码显示列表
            startY += VerticalSpacing * 2;
            listBoxBarcodes = new ListBox();
            listBoxBarcodes.Location = new Point(ControlStartX, startY);
            listBoxBarcodes.Width = 200;
            listBoxBarcodes.Height = 150;
            this.Controls.Add(listBoxBarcodes);

            // 创建“已录入的条码”标签
            var labelList = new Label();
            labelList.Text = "已录入的条码：";
            labelList.AutoSize = true;
            labelList.Location = new Point(ControlStartX + LabelOffsetX, startY + 5);
            this.Controls.Add(labelList);



            // 创建数量显示框
            startY += 160; // ListBox 高度较大，需增加更多偏移
            txtQuantity = new TextBox();
            txtQuantity.Location = new Point(ControlStartX, startY); // 控件 X 坐标已右移
            txtQuantity.Width = 200;
            txtQuantity.ReadOnly = true;
            this.Controls.Add(txtQuantity);

            // 创建“当前商品的个数”标签
            var labelQuantity = new Label();
            labelQuantity.Text = "当前商品的个数：";
            labelQuantity.AutoSize = true;
            labelQuantity.Location = new Point(ControlStartX + LabelOffsetX, startY + 5); // Label 位置不变
            this.Controls.Add(labelQuantity);

            // 创建“类型”标签和下拉框
            startY = txtQuantity.Bottom + 10;

            // 创建“类型”标签
            var labelType = new Label();
            labelType.Text = "类型：";
            labelType.AutoSize = true;
            labelType.Location = new Point(ControlStartX + LabelOffsetX, startY);
            this.Controls.Add(labelType);

            // 创建“类型”下拉框
            comboBoxType = new System.Windows.Forms.ComboBox();
            comboBoxType.Location = new Point(ControlStartX, startY);
            comboBoxType.Width = 200;
            comboBoxType.DropDownStyle = ComboBoxStyle.DropDownList; // 只能选择不能输入
            comboBoxType.Items.AddRange(new string[] { "入库", "出库" });
            comboBoxType.SelectedIndex = 0; // 默认选中“入库”
            this.Controls.Add(comboBoxType);

            // 创建“保存”按钮
            btnSave = new Button();
            btnSave.Text = "保存";
            btnSave.Location = new Point(ControlStartX, startY + 80);
            btnSave.Width = 100;
            btnSave.Click += BtnSave_Click;
            this.Controls.Add(btnSave);

            // 创建“关闭”按钮
            btnClose = new Button();
            btnClose.Text = "关闭";
            btnClose.Location = new Point(ControlStartX + 110, startY + 80);
            btnClose.Width = 100;
            btnClose.Click += BtnClose_Click;
            this.Controls.Add(btnClose);

            

            // 绑定事件
            txtBarcodeInput.KeyDown += txtBarcodeInput_KeyDown;
            listBoxBarcodes.SelectedIndexChanged += listBoxBarcodes_SelectedIndexChanged;
        }
        private async void BtnSave_Click(object sender, EventArgs e)
        {
            string selectedType = comboBoxType.SelectedItem?.ToString();

            if (string.IsNullOrEmpty(selectedType))
            {
                MessageBox.Show("请选择类型（入库/出库）");
                return;
            }

            if (_barcodeCountDict == null || !_barcodeCountDict.Any())
            {
                MessageBox.Show("没有可保存的数据");
                return;
            }

            try
            {
                foreach (var pair in _barcodeCountDict)
                {
                    string barcode = pair.Key;
                    int quantity = pair.Value;

                    // 调用接口保存数据，将 selectedType 传入
                    await SendToApiAsync(barcode, quantity, selectedType);
                }

                MessageBox.Show("所有条码已成功提交！");
                this.Close();
                ClearForm();
                SaveCompleted.Invoke();

            }
            catch (Exception ex)
            {
                MessageBox.Show($"提交失败：{ex.Message}");
            }
        }

        private void ClearForm()
        {
            listBoxBarcodes.Items.Clear();
            _barcodeCountDict.Clear();
            txtBarcodeInput.Clear();
            txtQuantity.Clear();
        }
        public class BarcodeQuantityDto
        {
                public string barcode { get; set; }
                public string documenttype { get; set; }
                public int num { get; set; }
        }
        private async Task SendToApiAsync(string barcode, int quantity, string type)
        {
            var request = new BarcodeQuantityDto
            {
                barcode = barcode,
                num = quantity,
                documenttype = type
            };

            string url = "http://localhost:5031/api/IOWareHouse/CreateIOWAREHOUSERECORDMODEL";
            //string url = "http://39.103.49.30:9981/api/IOWareHouse/CreateIOWAREHOUSERECORDMODEL";

            var content = new StringContent(
                JsonConvert.SerializeObject(request),
                Encoding.UTF8,
                "application/json"
            );

            HttpResponseMessage response = await _httpClient.PostAsync(url, content);

            if (!response.IsSuccessStatusCode)
            {
                string error = await response.Content.ReadAsStringAsync();
                throw new Exception($"条码 {barcode} 提交失败：{error}");
            }
        }
        private void BtnClose_Click(object sender, EventArgs e)
        {
            this.Close(); // 关闭当前窗体
        }
        private void txtBarcodeInput_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                string barcode = txtBarcodeInput.Text.Trim();
                if (!string.IsNullOrEmpty(barcode))
                {
                    UpdateBarcodeList(barcode);
                    txtBarcodeInput.Clear();
                    e.SuppressKeyPress = true;
                }
            }
        }

        private void UpdateBarcodeList(string barcode)
        {
            if (_barcodeCountDict.ContainsKey(barcode))
            {
                _barcodeCountDict[barcode]++;
            }
            else
            {
                _barcodeCountDict.Add(barcode, 1);
                listBoxBarcodes.Items.Add(barcode);
            }

            UpdateQuantityDisplay();
        }

        private void UpdateQuantityDisplay()
        {
            if (listBoxBarcodes.SelectedItem != null)
            {
                string selectedBarcode = listBoxBarcodes.SelectedItem.ToString();
                if (_barcodeCountDict.TryGetValue(selectedBarcode, out int count))
                {
                    txtQuantity.Text = count.ToString();
                }
            }
        }

        private void listBoxBarcodes_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateQuantityDisplay();
        }
    }
}